from sanic import Sanic
import aiomysql
import aioredis
from sanic import response
import asyncio

from product_api import SpecificMethoD

SpecificMethod = SpecificMethoD()

import json
from . import bp_product

@bp_product.route("/add_product_info",methods=['POST'])
async def product_type_info(request):

    if not request.method == 'POST':
    
        return response.json({
                'status': -1,
                'errorCode': 1,
                'errorMsg':f"请求方式error,request.method:{request.method}",
                'resultBody':None
            })

    product_info = request.form

    product_type = product_info.get('product_type')

    product_type_id = product_info.get('product_type_id')

    product_name = product_info.get('product_name')

    product_image = request.files.get("product_image")

    product_price = product_info.get('product_price')

    if not all([product_type_id,product_name,product_image,product_price]):

        return response.json({
                'status': -1,
                'errorCode': 2,
                'errorMsg':f"缺少参数{product_type_id,product_type,product_name,product_image,product_price}:{product_type_id,product_type,product_name,product_image,product_price}",
                'resultBody':None
            })


    with open("static/product_img/{}.jpg".format(product_name), 'wb') as f:

        # print(dir(product_image))

        info = f.write(product_image.body)

        if not info:

            return response.json({
                'status': -1,
                'errorCode': 11,
                'errorMsg':f"添加商品失败请检查product_image:{product_image}格式",
                'resultBody':None
            })

    product_image_url = "/static/product_img/{}".format(product_name)

    insert_product_work = await SpecificMethod.insert_info(sql="insert into product(product_name,product_image,product_price)values(%s,%s,%s);",args=(product_name,product_image_url,product_price))

    product_id = await SpecificMethod.select_one_info(sql="select id from product where product_name=%s",args=product_name)

    product_id = product_id.get('id')

    insert_intermediate_work = await SpecificMethod.insert_info(sql="insert into intermediate_table(product_id,product_type_id)values(%s,%s);",args=(product_id,product_type_id))

    if not insert_intermediate_work:
    
            return response.json({
                'status': -1,
                'errorCode': 11,
                'errorMsg':f"添加商品失败请检查product_type_id:{product_type_id}是否存在",
                'resultBody':None
            })

    await SpecificMethod.delete_str('product_all')

    await SpecificMethod.delete_str(product_type)

    return response.json({
                            'status': 1,
                            'errorCode': None,
                            'errorMsg':None,
                            'resultBody':'ok'
                        })

